<template>
  <lay-container :fluid="true" style="padding: 10px;padding-top: 10px;">
    <lay-card>
      <lay-row>
        <lay-col :md="24">
          <lay-col :md="4">
            <DeptTree @node-click="nodeClick"></DeptTree>
          </lay-col>
          <lay-col :md="20">
            <lay-col :md="24" class="toolbar">
              <lay-col :md="6">
                <lay-button type="primary" size="sm" @click="add" v-permission="PerKey.UserDept_AddOrEditView"
                  prefix-icon="layui-icon-addition">新增
                </lay-button>
                <lay-button size="sm" type="normal" @click="exportExcel()" prefix-icon="layui-icon-export">导出EXCEL
                </lay-button>
              </lay-col>
              <lay-col :md="18">                
                  <lay-form :model="queryModel" ref="layFormRef">
                    <lay-row>
                      <lay-col :md="4">
                        <lay-input size="sm" v-model="queryModel.userName" style="width: 90%"
                          placeholder="根据用户名查询"></lay-input>
                      </lay-col>
                      <lay-col :md="4">
                        <lay-input size="sm" v-model="queryModel.nickName" style="width: 90%"
                          placeholder="根据姓名查询"></lay-input>
                      </lay-col>
                      <lay-col :md="4">
                        <lay-select size="sm" v-model="queryModel.status" placeholder="用户状态" style="width: 90%">
                          <lay-select-option value="1" label="启用"></lay-select-option>
                          <lay-select-option value="0" label="禁用"></lay-select-option>
                        </lay-select>
                      </lay-col>
                      <lay-col :md="5">
                        <lay-button size="sm" type="primary" @click="GetList(queryModel)"
                          prefix-icon="layui-icon-search">查询</lay-button>
                        <lay-button size="sm" @click="reset">重置</lay-button>
                      </lay-col>
                    </lay-row>
                  </lay-form>                
              </lay-col>
            </lay-col>

            <lay-col :md="24">
              <lay-table :page="page" :columns="columns" :dataSource="dataSource" v-model:selectedKeys="selectedKeys"
                @change="change" :size="tablesize">
                <template v-slot:logininfo="{ data }">
                  {{ data.loginIp }} <br> {{ data.loginTime }}
                </template>
                <template v-slot:nickName="{ data }">
                  {{ data.nickName }} <br> {{ data.phone }}
                </template>
                <template v-slot:postName="{ data }">
                  {{ data.postName }} <br>({{ data.postCode }})
                </template>
                <template v-slot:userinfo="{ data }">
                  <lay-avatar :src="avatar(data.avatar)" radius></lay-avatar>
                </template>
                <template v-slot:sex="{ data }">
                  {{ data.sex == 1 ? "男" : "女" }}
                </template>
                <template v-slot:stat="{ data }">
                  <lay-switch v-model="data.status" onswitch-text="启用" unswitch-text="禁用"
                    @change="changeStatus($event, data.id)"></lay-switch>
                </template>
                <template v-slot:operator="{ data }">
                  <lay-button-group>
                    <lay-button type="primary" size="sm" @click="edit(data.id)"
                      v-permission="PerKey.UserDept_AddOrEditView" prefix-icon="layui-icon-edit">编辑
                    </lay-button>
                    <lay-button type="danger" size="sm" @click="del(data)" v-permission="PerKey.UserDept_Delete"
                      prefix-icon="layui-icon-delete">删除</lay-button>
                  </lay-button-group>
                </template>
              </lay-table>

            </lay-col>
          </lay-col>
        </lay-col>
      </lay-row>
    </lay-card>

    <lay-layer :title="addoredittip" v-model="modelVisible" :resize="true" :area="['1000px']">
      <lay-card style="padding:10px;">
        <lay-row space="10">
          <lay-form :model="form">
            <lay-col md="24">
              <lay-col md="8">
                <lay-form-item label="部门" prop="deptId" required>
                  <lay-select v-model="form.deptId" class="input-width">
                    <lay-select-option v-for="dept in userDepts" :value="dept.id" :label="dept.title">
                    </lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col md="8">
                <lay-form-item label="岗位" prop="postId" required>
                  <lay-select v-model="form.postId" class="input-width">
                    <lay-select-option v-for="post in userPosts" :value="post.id"
                      :label="post.postName + ' - ' + post.postCode">
                    </lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col md="8">
                <lay-form-item label="角色" prop="groupId" required>
                  <lay-select v-model="form.groupId" class="input-width">
                    <lay-select-option v-for="group in userGroups" :value="group.id" :label="group.groupName">
                    </lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
            </lay-col>
            <lay-col md="24" style="margin-top:30px;">
              <lay-col :md="8">
                <lay-form-item label="登录名" prop="userName" required>
                  <lay-col md="14">
                    <lay-input v-model="form.userName" class="input-width"></lay-input>
                  </lay-col>
                </lay-form-item>
              </lay-col>
              <lay-col :md="12">
                <lay-form-item label="姓名" prop="nickName" required required-error-message="姓名不能空且为中文">
                  <lay-col md="14">
                    <lay-input v-model="form.nickName" class="input-width"></lay-input>
                  </lay-col>
                </lay-form-item>
              </lay-col>
              <lay-col md="24" style="margin-top:30px;">
                <lay-form-item label="密码" prop="passWord">
                  <lay-col md="6">
                    <lay-input v-model="form.passWord" class="input-width"></lay-input>
                  </lay-col>
                  <lay-col md="18" class="tip">新增密码必填，修改用户可空</lay-col>
                </lay-form-item>
                <lay-form-item label="状态" prop="status">
                  <lay-col md="6" class="tip">
                    <lay-switch v-model="form.status" onswitch-text="启用" unswitch-text="禁用"></lay-switch>
                  </lay-col>
                  <lay-col md="6"> </lay-col>
                </lay-form-item>
              </lay-col>
              <lay-col :md="24" class="saveBtn">
                <lay-button @click="submitClick" type="primary" v-permission="PerKey.UserPost_AddOrEdit"
                  prefix-icon="layui-icon-ok">
                  {{ addoredittip }}
                </lay-button>
              </lay-col>
            </lay-col>
          </lay-form>
        </lay-row>
      </lay-card>
    </lay-layer>
  </lay-container>
</template>
<script lang="ts" setup>
import { reactive, ref, toRefs, watch } from "vue";
import { layer } from "@layui/layer-vue";
import { getList, delOne, chStatus, postAdd, putEdit, getEdit } from "../../../api/module/user/user";
import { PerKey } from "../../../library/permissionConst"
import { useRoute } from "vue-router";
import { systemConfig } from "../../../library/config"
import { User } from '../../../types/user'
import Uitl from '../../../library/Util'
import DeptTree from '../userdept/components/DeptTree.vue'
const selectedKeys = ref(["1"]);
const page = ref({ total: 0, limit: 10, current: 1, showCount: true, showRefresh: true, limits: [10, 15, 20, 50, 100, 200] });
const tablesize = ref('md');
const columns = [
  { title: "Id", width: "50px", key: "id", align: "center", },
  { title: "用户名", width: "80px", key: "userName", align: "center", },
  { title: "姓名", width: "120px", customSlot: "nickName", align: "center", },
  { title: "部门", width: "100px", key: "deptName", align: "center", },
  { title: "职务", width: "120px", customSlot: "postName", align: "center", },
  { title: "角色", width: "120px", key: "groupName", align: "center", },
  { title: "性别", width: "70px", align: "center", customSlot: "sex", },
  { title: "头像", width: "70px", align: "center", customSlot: "userinfo", },
  { title: "状态", customSlot: "stat", width: "80px", align: "center", },
  { title: "最新登录信息", customSlot: "logininfo", },
  { title: "操作", width: "180px", customSlot: "operator", key: "operator", align: "center", }
]
const dataSource = ref([])
const route = useRoute();
const avatar = (src: string) => {
  return src != null ? systemConfig.hostURL + src : null
}
//定义模型
const putData = reactive({
  formchange: {
    id: 0,
    Status: true,
  },
  queryModel: {
    deptId: 0,
    page: page.value.current,
    limit: page.value.limit,
    nickName: "",
    userName: "",
    status: 2,
    exportExcel: false,
  },
  form: <User><unknown>[]
})
const { formchange, form, queryModel } = toRefs(putData)

queryModel.value.deptId = route.query.deptId as unknown as number;

const changeStatus = function (val: boolean, id: number) {
  formchange.value.id = id;
  formchange.value.Status = val;
  chStatus(formchange.value).then((res) => {
    if (res.status == 1) {
      layer.msg(res.msg, { icon: 1, time: 1000 });
    } else {
      layer.msg(res.msg, { icon: 2 });
      return false;
    }
  });
}
//获取列表
const GetList = function (query: any) {
  if (query != null) {
    queryModel.value.userName = query.userName
    queryModel.value.nickName = query.nickName
    queryModel.value.status = query.status
  }
  getList(queryModel.value).then((res) => {
    if (res.status == 1) {
      //console.log(res)
      dataSource.value = res.data.data
      page.value.total = res.data.count
    }
  })
}
GetList(queryModel.value)

const layFormRef = ref();
const reset = function () {
  layFormRef.value.reset();
}

const exportExcel = () => {
  layer.confirm("确认导出所有列表", {
    title: "警告", move: "true", shade: "false", shadeClose: "true",
    btn: [{
      text: '确认', callback: (layerId: number) => {
        queryModel.value.exportExcel = true
        getList(queryModel.value).then((res) => {
          const { status, filePath, fileName } = res
          if (status == 1) {
            Uitl.downloadFileForUrl(filePath, fileName)
            layer.close(layerId);
          } else {
            layer.msg('导出失败');
          }
        })
      }
    }, {
      text: '取消', callback: function (layerId: number) {
        layer.close(layerId);
      }
    }]
  })
}

// 树组件点击
const nodeClick = async (node: any) => {
  queryModel.value.deptId = node.id;
  GetList(queryModel.value)
};

//监听参数变化

watch(() => route.query, (val: any) => {
  if (val.deptId != undefined) {
    queryModel.value.deptId = val.deptId
    GetList(queryModel.value)
  }
}, { immediate: true, deep: true })

const change = function ({ current, limit }: any) {
  queryModel.value.page = current
  queryModel.value.limit = limit
  GetList(queryModel.value);
};
//修改
const edit = function (id: number) {
  changeVisible(id)
}
//添加
const add = function () {
  changeVisible(0)
}
//删除
const del = function (data: any) {
  layer.confirm("确认删除ID: " + data.id + " " + data.nickName + " 用户吗？", {
    title: "警告", move: "true", shade: "false", shadeClose: "true",
    btn: [{
      text: '确认', callback: (layerId: number) => {
        delOne(data.id).then((res) => {
          if (res.status == 1) {
            layer.msg(res.msg, { time: 1000, icon: 1 }, () => {
              GetList(queryModel.value)
            });
          } else {
            layer.msg(res.msg, { time: 1000, icon: 2 });
          }
          layer.close(layerId);
        })
      }
    }, {
      text: '取消', callback: function (layerId: number) {
        layer.close(layerId);
      }
    }]
  })
}

//模态操作
let addoredittip = ref();

const modelVisible = ref(false)

const userGroups = ref({ targetList: [] as any, })
const userDepts = ref({ targetList: [] as any, })
const userPosts = ref({ targetList: [] as any, })

const changeVisible = function (id: number) {
  modelVisible.value = !modelVisible.value
  if (id == 0) {
    addoredittip.value = "新增用户";
    getEdit(id).then((res) => {
      if (res.status == 1) {
        userGroups.value = res.data.userGroups
        userDepts.value = res.data.userDepts
        userPosts.value = res.data.userPosts
        form.value = {
          id: 0,
          userName: "",
          passWord: "",
          nickName: "",
          status: true,
        }
      } else {
        layer.msg("获取基本信息失败！", { icon: 2 })
      }
    })
    return
  } else {
    addoredittip.value = "编辑用户";
    getEdit(id).then((res) => {
      if (res.status == 1) {
        let data = res.data.data
        userGroups.value = res.data.userGroups
        userDepts.value = res.data.userDepts
        userPosts.value = res.data.userPosts
        form.value = data
      } else {
        layer.msg("获取基本信息失败！", { icon: 2 })
      }
    })
    return
  }
}

const submitClick = function () {
  if (!form.value.userName || !form.value.nickName || !form.value.deptId || !form.value.postId || !form.value.groupId) {
    layer.msg("用户名、部门、职务、角色不能空")
    return
  }
  if (form.value.id == 0) {
    postAdd(form.value).then((res) => {
      done(res)
    });
  } else {
    putEdit(form.value).then((res) => {
      done(res)
    });
  }
};
const done = (res: any) => {
  if (res.status == 1) {
    layer.msg(res.msg, { time: 1000, icon: 1 }, () => {
      modelVisible.value = !modelVisible.value
      GetList(queryModel.value);
    });
  } else {
    layer.msg(res.msg, { icon: 2 });
    return false;
  }
}

</script>
<style scoped>
.input-width {
  width: 210px;
}

.toolbar {
  margin-bottom: 10px;
}
</style>